/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY. 
 * See the GNU General Public License for more details.
 * 
 * Copyright (C) 2011 CellObject.net
 */
package net.cellobject.javacodeformatter.view;

import net.cellobject.javacodeformatter.model.FormatterManager;

import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.part.ResourceTransfer;

/**
 * Provide support for dragging the objects into the Favorites view from another view.
 */
public class FormatterDropTarget extends DropTargetAdapter {
	public FormatterDropTarget(final TableViewer viewer) {
		final DropTarget target = new DropTarget(viewer.getControl(), DND.DROP_MOVE | DND.DROP_COPY);
		target.setTransfer(new Transfer[]{ResourceTransfer.getInstance(), JavaUI.getJavaElementClipboardTransfer()});
		target.addDropListener(this);
	}

	@Override
	public void dragEnter(final DropTargetEvent event) {
		if ( (event.detail == DND.DROP_MOVE) || (event.detail == DND.DROP_DEFAULT)) {
			if ( (event.operations & DND.DROP_COPY) != 0) {
				event.detail = DND.DROP_COPY;
			} else {
				event.detail = DND.DROP_NONE;
			}
		}
	}

	@Override
	public void drop(final DropTargetEvent event) {
		FormatterManager manager = FormatterManager.getManager();
		if (JavaUI.getJavaElementClipboardTransfer().isSupportedType(event.currentDataType) && (event.data instanceof IJavaElement[])) {
			manager.addFavorites((IJavaElement[])event.data);
			event.detail = DND.DROP_COPY;
		} else if (ResourceTransfer.getInstance().isSupportedType(event.currentDataType) && (event.data instanceof IResource[])) {			
			IResource[] resources = (IResource[])event.data;
			for(IResource resource: resources){
				//Only JAVA or XML files will be added to the formatter list when dragging and dropping
				if(resource.getFileExtension().equalsIgnoreCase("java") || resource.getFileExtension().equalsIgnoreCase("xml")){ 
					manager.addFavorites((IResource[])event.data);
					event.detail = DND.DROP_COPY;
				}				
			}			
		} else{
			event.detail = DND.DROP_NONE;
		}		
	}
	
}
